<?php
namespace app\api\controller;

use think\Controller;

/**
 * 通用上传api
 */
class Upload extends Controller
{

    public function imageTmp()
    {
        $photo = input('photo', 'photo');
        if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $photo, $result)) {
            $base64 = str_replace($result[1], '', $photo);
            $image = base64_decode($base64);
            if (!$image) {
                return json(['code' => -1, 'msg' => '图像格式不对(文件大小超过2M会导致文件上传失败)']);
            }
            $imageInfo = getimagesizefromstring($image);
            if (!in_array($imageInfo['mime'], ['image/png', 'image/jpg', 'image/bmp', 'image/jpeg'])) {
                return json(['code' => -1, 'msg' => '文件格式不对']);
            }
            if (strlen($image) / 1024 / 1024 > 2) {
                return json(['code' => -1, 'msg' => '文件大小不得超过2M']);
            }
            $filename = $this->formatFileName(substr($imageInfo['mime'], 6));
            $path = ROOT_PATH . 'public/uploads/temp/image';
            if (!file_exists($path)) {
                mkdir($path);
            }
            file_put_contents($path . '/'. $filename, $image);
            return json(['code' => 0, 'path' => config('subroot'). '/uploads/temp/image/'. $filename]);
        } else {
            return json(['code' => -1, 'msg' => '图像格式不对(文件大小超过2M会导致文件上传失败)']);
        }
    }
    /**
     * 返回特定的文件名格式
     * @author cuibo weiai525@outlook.com at 2016-11-07
     * @param  string $extension 后缀名，不带 ‘.’
     * @return string            文件名
     */
    private function formatFileName($extension)
    {
        return date('YmdHis') . get_random_string(15) . '.' . $extension;
    }

}
